﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SurfaceAd.Common;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

/**
 * 创建时间：2014/9/25 15:57:26
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    internal enum ImageStatus
    {
        Success,
        Failure
    }
    internal sealed class StorageCachedImage : BitmapSource
    {
        public delegate void StorageImageStatus(ImageStatus imageStatus);
        public event StorageImageStatus OnStorageImageStatus;

        private readonly Uri uriSource;
        private readonly string filename;

        StorageFolder storage = Windows.Storage.ApplicationData.Current.LocalFolder;

        public StorageCachedImage()
        {
        }

        public StorageCachedImage(Uri uriSource)
            : this()
        {
            this.uriSource = uriSource;
            //文件路径            
            filename = string.Format("imagead_{0}_{1}", MD5.GetMd5String(uriSource.AbsoluteUri), uriSource.AbsolutePath.TrimStart('/').Replace('/', '_'));
            //filePath = Path.Combine(Constants.AdCacheDirectory, filename);
            //
            DownloadImage();
        }

        async void DownloadImage()
        {
            try
            {
                storage = await storage.CreateFolderAsync(Constants.AdCacheDirectory, CreationCollisionOption.OpenIfExists);
                //foreach (StorageFile file in await storage.GetFilesAsync())
                //{
                //    LogHelper.LogMessage(string.Concat("文件名：" + file.Name));
                //}
                await SaveImageFromUrl(uriSource, filename);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "DownloadImage");
                if (OnStorageImageStatus != null)
                {
                    OnStorageImageStatus(ImageStatus.Failure);
                }
            }
        }

        async void LoadImageFromLocalFile()
        {
            try
            {
                //StorageFolder folder = await storeage.CreateFolderAsync(Constants.AdCacheDirectory, CreationCollisionOption.OpenIfExists);                
                StorageFile file = await storage.GetFileAsync(this.filename);
                this.SetSource(await file.OpenReadAsync());
                if (OnStorageImageStatus != null)
                {
                    OnStorageImageStatus(ImageStatus.Success);
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "LoadImageFromLocalFile");
                if (OnStorageImageStatus != null)
                {
                    OnStorageImageStatus(ImageStatus.Failure);
                }
            }
        }



        private async Task SaveImageFromUrl(Uri uri, string filename)
        {
            try
            {
                bool IsFileExists = false;
                try
                {
                    await storage.GetFileAsync(filename);
                    IsFileExists = true;
                    LogHelper.LogError("文件存在：" + filename);
                    LoadImageFromLocalFile();
                }
                catch
                {
                    LogHelper.LogError("文件不存在：" + filename);
                }
                if (!IsFileExists)
                {
                    var rass = RandomAccessStreamReference.CreateFromUri(uri);
                    IRandomAccessStream inputStream = await rass.OpenReadAsync();
                    Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));

                    //获取图片扩展名的Guid                    
                    StorageFile outputFile = await storage.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
                    using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        Stream output = WindowsRuntimeStreamExtensions.AsStreamForWrite(outputStream.GetOutputStreamAt(0));
                        await input.CopyToAsync(output);
                        output.Dispose();
                        input.Dispose();
                        LoadImageFromLocalFile();
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "SaveImageFromUrl");
                if (OnStorageImageStatus != null)
                {
                    OnStorageImageStatus(ImageStatus.Failure);
                }
            }
        }
    }
}
